﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExitGames;
using Photon.SocketServer;
using NArms.AutoMapper;
using BloxServer2012;
using BloxDTO;

namespace BloxServer2012
{
    public class Commands
    {
        public static OperationResponse Login(ServerPeer peer, object username, object password, OperationResponse response)
        {
            if (!DataAccess.Database.Players.Any(u => u.Name == (string)username))
            {
                Server.logger.Error("Login: Unknown user: " + username);
                response.DebugMessage = "Unknown User";
                response.ReturnCode = ReturnCode.UnknownUser;
                return response;
            }
            peer.Username = username as string;
            ServerPeer.Players.Add(peer);
            Server.logger.Info("Login: Success: " + username);
            response.ReturnCode = ReturnCode.Success;
            return response;
        }

        public static OperationResponse Logout(ServerPeer serverPeer, object username, OperationResponse response)
        {
            if (!ServerPeer.Players.Any(p => p == serverPeer))
            {
                Server.logger.Error("Logout: User not found: " + username);
                response.DebugMessage = "Unknown User";
                response.ReturnCode = ReturnCode.UnknownUser;
                return response;
            }
            ServerPeer.Players.Remove(serverPeer);
            Server.logger.Error("Logout: Success: " + username);
            response.ReturnCode = ReturnCode.Success;
            return response;
        }

        public static OperationResponse GetWorld(object name, OperationResponse response)
        {
            if (!DataAccess.Database.Worlds.Any(w => w.Name == (string)name))
            {
                Server.logger.Error("GetWorld: Unknown world: " + name);
                response.DebugMessage = "Unknown World";
                response.ReturnCode = ReturnCode.UnknownWorld;
                return response;
            }
            Server.logger.Info("GetWorld: Success: " + name);
            var DBworld = DataAccess.Database.Worlds.FirstOrDefault(w => w.Name == (string)name);
            var world = MapExtensions.MapTo<BloxDTO.World>(DBworld);
            response.SetParameters(world);
            response.ReturnCode = ReturnCode.Success;
            return response;
        }
    }
}
